﻿using System;
using EnterpriseFramework.Configuration;
using System.Reflection;

namespace EnterpriseFramework.DataAccess.Provider
{
    public class DALAdapter<T>
    {
        private static ICompatibility newInstatnce = null;
        private static DBProvider<T> _provider;
        public DBProvider<T> provider
        {
            get
            {
                if (_provider == null)
                    _provider = new DBProvider<T>(newInstatnce.Connection);
                return _provider;
            }
        }

        public DALAdapter()
        {
            if (newInstatnce == null)
            {
                newInstatnce = GetDefaultProvider();
            }
        }

        public DataCollection<T> Select(Table table, Query query)
        {
            QueryResult qr = null;
            if (query != null)
                qr = query.QResult;

            var cmd = newInstatnce.GetSelectCommand(table, qr);
            return provider.ExecuteReader(cmd, table.Columns);
        }

        //public void Select(Table table, Query query)
        //{
        //    var cmd = Configurations.ConfigurationManagers.Providers.DefaultProvider.GetSelectCommand(table, query);
        //    provider.ExecuteReader(cmd, table.Columns);
        //}

        private ICompatibility GetDefaultProvider()
        {
            Providers providerConfig = new Providers();
            ConfigurationFactory config = new ConfigurationFactory();
            providerConfig = config.GetProviders();
            foreach (EnterpriseFramework.Configuration.Provider provider in providerConfig.ProviderList)
            {
                if (string.Compare(providerConfig.Default, provider.Name, true) == 0)
                {
                    ICompatibility compatibility = null;
                    if (!string.IsNullOrEmpty(provider.ProviderClass) && string.IsNullOrEmpty(provider.ExternalAssembly))
                        compatibility = Activator.CreateInstance(Type.GetType(provider.ProviderClass)) as ICompatibility;
                    else if (!string.IsNullOrEmpty(provider.ExternalAssembly))
                    {
                        Assembly assembly = Assembly.LoadFrom(provider.ExternalAssembly);
                        compatibility = assembly.CreateInstance(provider.ProviderClass) as ICompatibility;
                    }
                    compatibility.Connection.ConnectionString = provider.ConnectionString;
                    return compatibility;
                }
            }
            return default(ICompatibility);
        }
    }
}
